<?php

namespace App\Http\Controllers\Admin;

use App\Models\Images;
use App\Repositories\ImagesRepositories;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class ImagesController extends BaseController
{
    public function __construct(ImagesRepositories $imagesRepositories)
    {
        $this->imagesRepositories = $imagesRepositories;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('admin.images.index');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.page.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

        $ret = $this->imagesRepositories->save($request->all());

        if($ret)
        {
            return redirect()->route('admin.pages')->with(['success'=>'添加完成']);
        }
        return redirect()->back()->with(['success'=>'系统错误']);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */

    public function destroy()
    {
        $ids=request()->input('ids');

        if(empty($ids))
        {
            return response()->json([
                'code' => 0,
                'msg'   => '请选择删除项！',
            ]);
        }

        if(!is_array($ids))
        {
            return response()->json([
                'code' => 0,
                'msg'   => '非法参数！',
            ]);
        }

        $ret =$this->imagesRepositories->delete($ids);
        if($ret)
        {
            return response()->json([
                'code' => 0,
                'msg'   => '删除成功！',
            ]);
        }
        return response()->json([
            'code' => -1,
            'msg'   => '删除失败！',
        ]);
    }

    public function data(Request $request)
    {
        $data = $request->all();
        $res = $this->imagesRepositories->search($data);
        $data = [
            'code' => 0,
            'msg'   => '正在请求中...',
            'count' => $res['total'],
            'data'  => $res['data']
        ];
        return response()->json($data);
    }

    public function manage(Request $request)
    {
        header("Content-Type: text/html; charset=utf-8");
        date_default_timezone_set("Asia/Chongqing");
        $config=public_path('static/admin/ue/config.json');
        $CONFIG = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents($config)), true);
        //dd($CONFIG);
        $action = $request->input('action');
        switch ($action) {
            case 'config':
                $result = json_encode($CONFIG);
                break;
            /* 上传图片 */
            case 'uploadimage':
                return $this->uploadImage();
            /* 列出图片 */
            case 'listimage':
                return $this->listImage();
                break;
            /* 列出图片 */
            case 'search':
                return $this->listImage();
                break;
            default:
                $result = json_encode(array(
                    'state' => '请求地址出错'
                ));
                break;
        }
        $callback = $request->input('callback');
        /* 输出结果 */
        if (isset($callback)) {
            if (preg_match("/^[\w_]+$/", $callback)) {
                echo htmlspecialchars($callback) . '(' . $result . ')';
            } else {
                echo json_encode(array(
                    'state' => 'callback参数不合法'
                ));
            }
        } else {
            echo $result;
        }
    }

    public function uploadImage()
    {
        $request=\request();
        //上传文件最大大小,单位M
        $maxSize = 10;
        //支持的上传图片类型
        $allowed_extensions = ["png", "jpg", "gif"];
        //返回信息json
        $data = ['code'=>200, 'msg'=>'上传失败', 'data'=>''];
        $file = $request->file('upfile');



        //检查文件是否上传完成
        if ($file->isValid()){
            //检测图片类型
            $ext = $file->getClientOriginalExtension();
            if (!in_array(strtolower($ext),$allowed_extensions)){
                $data['msg'] = "请上传".implode(",",$allowed_extensions)."格式的图片";
                return response()->json($data);
            }
            //检测图片大小
            //if ($file->getSize() > $maxSize*1024*1024){
            if ($file->getSize() > $maxSize*1024*1024)
            {
                $data['state'] = "图片大小限制".$maxSize."M";
                return response()->json($data);
            }
        }else{
            $data['msg'] = $file->getErrorMessage();
            return response()->json($data);
        }
        $newFile = date('Y-m-d')."_".time()."_".uniqid().".".$file->getClientOriginalExtension();
//        $disk = QiniuStorage::disk('qiniu');
        $disk = Storage::disk('uploads');

        $res = $disk->put($newFile,file_get_contents($file->getRealPath()));
        if($res){

            $imageId=md5(get_hash($file->getClientOriginalName()));
            $url =asset('').'uploads/'.$newFile;
            $data = [
                'image_id'  => $imageId,
                'name'   =>$file->getClientOriginalName(),
                'size'  => $file->getSize(),
                'originalName'  => $newFile,
                'state'  => 'SUCCESS',
                'type'  => $res,
                'url' => $url
            ];
            $saveData=[
                'id'  => $imageId,
                'name'   =>$file->getClientOriginalName(),
                'url'  => $url,
                'path'  => public_path('uploads').'/'.$newFile,
                'type'   =>'local',
                'created_at'=>date('Y-m-d H:i:s',time())

            ];
            $this->imagesRepositories->save($saveData);

        }else{
            $data['data'] = $file->getErrorMessage();
        }
        return response()->json($data);

    }
    protected function listImage()
    {
        $request=\request();
        $data = $request->all();
        $data['limit'] = $request->input('size',50);
        $data['page'] = $request->input('page',1);
        $res = $this->imagesRepositories->search($data);
        //dd($res);
        $imageData=[];
        foreach ($res['data'] as $key => $val) {
            if ($val['type'] == 'local') {
                $val['url'] = $val['url'];
            }
            $imageData[$key]['url']      = $val['url'];
            $imageData[$key]['image_id'] = $val['id'];
            $imageData[$key]['name']     = $val['name'];
            $imageData[$key]['title']     = $val['name'];
            $imageData[$key]['created_at']    = $val['created_at'];
        }

        $data = [
            'start' => $data['page'],
            'state'   => 'SUCCESS',
            'total' => $res['total'],
            'last_page'=>$res['last_page'],
            'list'  => $imageData
        ];
        return response()->json($data);
    }
}
